package bud.taskmanager.task.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

import bud.taskmanager.task.dto.Task;


@Repository(value = "TaskDao")
public class TaskDao {

	@Autowired
	private SimpleJdbcTemplate template;

	public List<Task> findAllTasks() {
		return template
				.query("SELECT ID, TRACKER_ID, PROJECT_ID, SUBJECT, DESCRIPTION, DUE_DATE, CATEGORY_ID, STATUS_ID, ASSIGNED_TO_ID, PRIORITY_ID, AUTHOR_ID, CREATED_ON, UPDATED_ON, START_DATE, DONE_RATIO, ESTIMATED_HOURS, PARENT_ID, ROOT_ID FROM TASKS ORDER BY CREATED_ON DESC",
						new BeanPropertyRowMapper<Task>(Task.class));
	}

	public Task findTask(int id) {
		return template
				.queryForObject(
						"SELECT ID, TRACKER_ID, PROJECT_ID, SUBJECT, DESCRIPTION, DUE_DATE, CATEGORY_ID, STATUS_ID, ASSIGNED_TO_ID, PRIORITY_ID, AUTHOR_ID, CREATED_ON, UPDATED_ON, START_DATE, DONE_RATIO, ESTIMATED_HOURS, PARENT_ID, ROOT_ID FROM TASKS WHERE ID=?",
						new BeanPropertyRowMapper<Task>(Task.class), id);
	}

	public void createTask(Task task) {
		template.update(
				"INSERT INTO TASKS (TRACKER_ID, PROJECT_ID, SUBJECT, DESCRIPTION, DUE_DATE, CATEGORY_ID, STATUS_ID, ASSIGNED_TO_ID, PRIORITY_ID, AUTHOR_ID, CREATED_ON, UPDATED_ON, START_DATE, DONE_RATIO, ESTIMATED_HOURS, PARENT_ID, ROOT_ID) VALUES "
						+ "(:trackerId, :projectId, :subject, :description, :dueDate, :categoryId, :statusId, :assignedToId, :priorityId, :authorId, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, :startDate, :doneRatio, :estimatedHours, :parentId, :rootId)",
				new BeanPropertySqlParameterSource(task));
	}

	public void updateTask(Task task) {
		template.update(
				"UPDATE TASKS SET SUBJECT=:subject, DESCRIPTION=:description WHERE ID=:id",
				new BeanPropertySqlParameterSource(task));
	}

	public void deleteTask(int id) {
		template.update("DELETE FROM TASKS WHERE ID=?", id);
	}

}
